﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.MessageCommand;
using D.Medicalcare.Read.API.Application.Command.PatientCommand;
using D.Medicalcare.Read.API.Application.Handler.PatientHandler;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.MessageHandler
{
    public class GetMessageHandler : IRequestHandler<GetMessageCommand, APIPaging<Message>>
    {
        private readonly IBaseRepository<Message> prep;
        private readonly ILogger<GetMessageHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="prep">仓储</param>
        /// <param name="logger">日志</param>
        public GetMessageHandler(IBaseRepository<Message> prep, ILogger<GetMessageHandler> logger)
        {
            this.prep = prep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public async Task<APIPaging<Message>> Handle(GetMessageCommand request, CancellationToken cancellationToken)
        {
            APIPaging<Message> result = new APIPaging<Message>();
            try
            {
                var list = prep.GetAll().Where(x=>!x.IsDeleted);
                if (!string.IsNullOrEmpty(request.Title))
                {
                    list = list.Where(x=>x.Title==request.Title);

                }
                result.Code = APIEnum.Success;
                result.Msg = "查询成功";
                logger.LogInformation(result.Msg);
                result.TotalCount = list.Count();
                result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0/request.PageSize);
                result.Data = list.OrderBy(x=>x.MessageId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError("查询异常" + ex.Message);

                throw;
            }

        }
    }
}

